package com.erp.MyCamera;

import android.app.Activity;
import androidx.appcompat.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.erp.activity.DanjianivActivity;
import com.erp.bean.ProdyctionClientBean;
import com.erp.Myapp;
import com.erp.R;
import com.erp.util.Myutil;

import net.bither.util.NativeUtil;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Locale;

import static android.provider.Telephony.TextBasedSmsColumns.STATUS_NONE;
import static com.erp.Myapp.sp;

public class CameraActivity extends Activity implements View.OnTouchListener,OnClickListener ,SensorEventListener {

	public static final String CAMERA_PATH_VALUE1 = "PHOTO_PATH";
	public static final String CAMERA_PATH_VALUE2 = "PATH";
	public static final String CAMERA_TYPE = "CAMERA_TYPE";
	public static final String CAMERA_RETURN_PATH = "return_path";

	private int PHOTO_SIZE_W = 2000;
	private int PHOTO_SIZE_H = 2000;
	public static final int CAMERA_TYPE_1 = 1;
	public static final int CAMERA_TYPE_2 = 2;
	private final int PROCESS = 1;
	private CameraPreview1 preview;
	private Camera camera;
	private Context mContext;
	private View focusIndex;
	private int mCurrentCameraId = 0; // 1是前置 0是后置
	private SurfaceView mSurfaceView;
	private CameraGrid mCameraGrid;

	private int type = 1;	//引用的矩形框

	private Button mBtnSearch;
	private OrientationEventListener mOrEventListener; // 设备方向监听器
	private int code=0;
    private int hengshu=0;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;

		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		//getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//全屏
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//拍照过程屏幕一直处于高亮
		setContentView(R.layout.camera_home);
		file=getIntent().getStringExtra("file");
		type = getIntent().getIntExtra(CAMERA_TYPE, CAMERA_TYPE_2);
//		if(sp.getBoolean("apd",false)){
//			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
//		}else {
//			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
//		}
		code=getIntent().getIntExtra("code",code);
		initView();
		InitData();
		startOrientationChangeListener();
	}


	private final void startOrientationChangeListener() {
		mOrEventListener = new OrientationEventListener(this) {
			@Override
			public void onOrientationChanged(int rotation) {
				if(!sp.getBoolean("apd",false)) {
					if ((rotation > 45) && (rotation < 135)) {
						hengshu = 90;
					} else if ((rotation > 225) && (rotation < 315)) {// landscape
						hengshu = 270;
					}
				}
			}
		};
		mOrEventListener.enable();
	}
	private void initView() {
		focusIndex = findViewById(R.id.focus_index);
		mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
		mCameraGrid = (CameraGrid) findViewById(R.id.camera_grid);
	}


	private void InitData() {
		preview = new CameraPreview1(this, mSurfaceView);
		preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		((FrameLayout) findViewById(R.id.layout)).addView(preview);
		preview.setKeepScreenOn(true);
		mSurfaceView.setOnTouchListener(this);
		mCameraGrid.setType(type);
	}




	private Handler handler = new Handler();

	private void takePhoto() {
		try {

			camera.takePicture(shutterCallback, rawCallback, jpegCallback);

		} catch (Throwable t) {
			t.printStackTrace();
			Toast.makeText(getApplication(), "拍照失败，请重试！", Toast.LENGTH_LONG)
			.show();
			try {
				camera.startPreview();
			} catch (Throwable e) {

			}
		}
	}



	@Override
	protected void onResume() {
		super.onResume();
        if(sp.getBoolean("apd",false)){
            hengshu=-90;
        }else{
            hengshu=0;
        }
		int numCams = Camera.getNumberOfCameras();
		if (numCams > 0) {
			try {
				mCurrentCameraId = 0;
				camera = Camera.open(mCurrentCameraId);
//				camera.startPreview();
				preview.setCamera(camera);
				preview.reAutoFocus();
			} catch (RuntimeException ex) {
//				Toast.makeText(mContext, "未发现相机", Toast.LENGTH_LONG).show();
			}
		}

	}



	@Override
	protected void onPause() {
		if (camera != null) {
			camera.stopPreview();
			preview.setCamera(null);
			camera.release();
			camera = null;
			preview.setNull();
		}
		super.onPause();

	}


	private void resetCam() {
		camera.startPreview();
		preview.setCamera(camera);
	}


	ShutterCallback shutterCallback = new ShutterCallback() {
		public void onShutter() {
		}
	};


	PictureCallback rawCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
		}
	};


	PictureCallback jpegCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {

			new SaveImageTask(data).execute();
			resetCam();
		}
	};


	@Override
	public boolean onTouch(View v, MotionEvent event) {
		try {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
				preview.pointFocus(new PointF(event.getRawX(),event.getRawY()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(
				focusIndex.getLayoutParams());
		layout.setMargins((int) event.getX() - 60, (int) event.getY() - 60, 0,0);

		focusIndex.setLayoutParams(layout);
		focusIndex.setVisibility(View.VISIBLE);

		ScaleAnimation sa = new ScaleAnimation(3f, 1f, 3f, 1f,
				ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
				ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
		sa.setDuration(800);
		focusIndex.startAnimation(sa);
		handler.postAtTime(new Runnable() {
			@Override
			public void run() {
				focusIndex.setVisibility(View.INVISIBLE);
			}
		}, 800);
		return false;
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		/*case R.id.camera_back:
			setResult(0);
			finish();
			break;*/
		case R.id.action_button:
			takePhoto();
			break;
		}
	}
	Calendar mCalendar;
	private int STATUE = STATUS_NONE;
	private int mX, mY, mZ;
	public static final int STATUS_MOVE = 2;
	private long lastStaticStamp = 0;
	boolean canFocusIn = false;  //内部是否能够对焦控制机制
	public static final int DELEY_DURATION = 500;
	public static final int STATUS_STATIC = 1;
	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor == null) {
			return;
		}
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			int x = (int) event.values[0];
			int y = (int) event.values[1];
			int z = (int) event.values[2];
			mCalendar = Calendar.getInstance();
			long stamp = mCalendar.getTimeInMillis();// 1393844912

			int second = mCalendar.get(Calendar.SECOND);// 53

			if (STATUE != STATUS_NONE) {
				int px = Math.abs(mX - x);
				int py = Math.abs(mY - y);
				int pz = Math.abs(mZ - z);
//                Log.d(TAG, "pX:" + px + "  pY:" + py + "  pZ:" + pz + "    stamp:"
//                        + stamp + "  second:" + second);
				double value = Math.sqrt(px * px + py * py + pz * pz);
				if (value > 1.4) {
//                    textviewF.setText("检测手机在移动..");
//                    Log.i(TAG,"mobile moving");
					STATUE = STATUS_MOVE;
				} else {
//                    textviewF.setText("检测手机静止..");
//                    Log.i(TAG,"mobile static");
					//上一次状态是move，记录静态时间点
					if (STATUE == STATUS_MOVE) {
						lastStaticStamp = stamp;
						canFocusIn = true;
					}

					if (canFocusIn) {
						if (stamp - lastStaticStamp > DELEY_DURATION) {
							//移动后静止一段时间，可以发生对焦行为
								canFocusIn = false;
//                                onCameraFocus();
							int screenWidth = Myapp.mScreenWidth;
							PointF point = new PointF(screenWidth / 2, screenWidth / 2);

							try {
								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
									preview.pointFocus(point);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}

//                                Log.i(TAG,"mobile focusing");
						}
					}

					STATUE = STATUS_STATIC;
				}
			} else {
				lastStaticStamp = stamp;
				STATUE = STATUS_STATIC;
			}

			mX = x;
			mY = y;
			mZ = z;
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	//处理拍摄的照片
	private class SaveImageTask extends AsyncTask<Void, Void, String> {
		private byte[] data;

		SaveImageTask(byte[] data) {
			this.data = data;
		}

		@Override
		protected String doInBackground(Void... params) {
			// Write to SD Card
			String path = "";
			try {

				showProgressDialog("处理中");
				Log.d("TAAAG","data="+data.length);
				path = saveToSDCard(data);
				NativeUtil.compressBitmap(path,path);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
			}
			return path;
		}


		@Override
		protected void onPostExecute(String path) {
			super.onPostExecute(path);

			if (!TextUtils.isEmpty(path)) {
				Intent intent=new Intent(CameraActivity.this, DanjianivActivity.class);
				intent.putExtra("url",path);
				intent.putExtra("code",code);
				startActivityForResult(intent,1);
				dismissProgressDialog();
			} else {
				Toast.makeText(getApplication(), "拍照失败，请稍后重试！",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	private AlertDialog mAlertDialog;

	private void dismissProgressDialog() {
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (mAlertDialog != null && mAlertDialog.isShowing()
						&& !CameraActivity.this.isFinishing()) {
					mAlertDialog.dismiss();
					mAlertDialog = null;
				}
			}
		});
	}

	private void showProgressDialog(final String msg) {
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mAlertDialog = Myutil.showupdatedialog(mContext, "处理中", false);
//				if (mAlertDialog == null) {
//					mAlertDialog = new GenericProgressDialog(
//							CameraActivity.this);
//				}
//				mAlertDialog.setMessage(msg);
//				((GenericProgressDialog) mAlertDialog)
//				.setProgressVisiable(true);
//				mAlertDialog.setCancelable(false);
//				mAlertDialog.setOnCancelListener(null);
//				mAlertDialog.show();
//				mAlertDialog.setCanceledOnTouchOutside(false);
			}
		});
	}


	/**
	 * 将拍下来的照片存放在SD卡中
	 */
	public String saveToSDCard(byte[] data) throws IOException {
		Bitmap croppedImage;
		// 获得图片大小
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, options);
		// PHOTO_SIZE = options.outHeight > options.outWidth ? options.outWidth
		// : options.outHeight;
		PHOTO_SIZE_W = options.outWidth;
		PHOTO_SIZE_H = options.outHeight;
		options.inJustDecodeBounds = false;
		Rect r = new Rect(0, 0, PHOTO_SIZE_W, PHOTO_SIZE_H);
		try {
			croppedImage = decodeRegionCrop(data, r);
		} catch (Exception e) {
			Log.d("TAAAG",e.toString());
			return null;
		}
		String imagePath = "";
		try {
			imagePath = saveToFile(croppedImage);
		} catch (Exception e) {
			Log.d("TAAAG",e.toString()+"------------------------");
			e.printStackTrace();
		}
		croppedImage.recycle();
		return imagePath;
	}



	private Bitmap decodeRegionCrop(byte[] data, Rect rect) {
		InputStream is = null;
		System.gc();
		Bitmap croppedImage = null;
		try {
			is = new ByteArrayInputStream(data);
			BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is,false);
			try {
				croppedImage = decoder.decodeRegion(rect,
						new BitmapFactory.Options());
			} catch (IllegalArgumentException e) {
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {

		}
		Matrix m = new Matrix();
		m.setRotate(90, PHOTO_SIZE_W / 2, PHOTO_SIZE_H / 2);
		if (mCurrentCameraId == 1) {
			m.postScale(1, -1);
		}
		Bitmap rotatedImage = Bitmap.createBitmap(croppedImage, 0, 0,
				PHOTO_SIZE_W, PHOTO_SIZE_H, m, true);
		if (rotatedImage != croppedImage)
			croppedImage.recycle();
		return rotatedImage;
	}


	private String file;
	private String name;
	// 保存图片文件
	private  String saveToFile(Bitmap croppedImage) throws IOException {
		String name = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
		Log.d("TAAAG","file="+file.toString());
		File outFile = new File( new File(file), name);
		FileOutputStream outputStream = new FileOutputStream(outFile); // 文件输出流
		if(hengshu!=0) {
			Matrix matrix = new Matrix();
			matrix.postRotate(hengshu);
			croppedImage = Bitmap.createBitmap(croppedImage, 0, 0,croppedImage.getWidth(),croppedImage.getHeight() , matrix, true);
		}
		croppedImage.compress(Bitmap.CompressFormat.JPEG, 70, outputStream);
		outputStream.flush();
		outputStream.close();
		return outFile.getAbsolutePath();
	}



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			setResult(0);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("TAAAG","CAMERAACTIVITY");
		if (requestCode == PROCESS) {
			if (resultCode == RESULT_OK) {
				Intent intent = new Intent();
				File dir = new File(data.getStringExtra(CAMERA_PATH_VALUE2));
				int code=data.getIntExtra("code",0);
				Log.d("TAAAG","code="+code);
				if(code==2) {
					ProdyctionClientBean.guimingxi cid = data.getParcelableExtra("cid");
					intent.putExtra("cid",cid);
				}
				intent.putExtra("dir",dir.toString());
				setResult(RESULT_OK, intent);
				finish();
			} else {
				if (data != null) {
					File dir = new File(data.getStringExtra(CAMERA_PATH_VALUE2));
					if (dir != null) {
						dir.delete();
					}
				}
			}
		}
	}
}
